﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
using System.Xml.Linq;

namespace AgendaTelefonica.DataAcessObject
{
    public static class DataBaseConnection
    {
        public static String strPathDataBase;
        private static XDocument xmlDataBase;

        public static XDocument DataBase
        {
            get { return DataBaseConnection.xmlDataBase; }
        }
        public static void LoadDataBase()
        {
            try
            {
                xmlDataBase = XDocument.Load(strPathDataBase);
            }
            catch (DirectoryNotFoundException ex)
            {
                Directory.CreateDirectory("Data");
                CreateDataBase();
            }
            catch (FileNotFoundException ex)
            {
                CreateDataBase();
            }
        }
        private static void CreateDataBase()
        {
            File.Create(strPathDataBase);
            xmlDataBase = new XDocument();
            xmlDataBase.Add(new XElement("Contatos"));
            xmlDataBase.Save(strPathDataBase);
        }
        public static void SaveDataBase()
        {
            xmlDataBase.Save(strPathDataBase);
        }
        public static Int32 GetNexCodigo(String _strTable)
        {
            Int32 intCodigo = 1;
            List<XElement> element = (from c in xmlDataBase.Root.Elements(_strTable) select c).ToList();
            if (element.Count > 0)
            {
                var maxCodigo = element.Select(item => (Int32)item.Element("Codigo")).Max();
                intCodigo = maxCodigo + 1;
            }
            return intCodigo;
        }
    }
}
